#!/bin/bash
# 重启后验证脚本 - 检查CH9344驱动和串口设备是否正常

echo "=== 重启后配置验证脚本 ==="
echo ""

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "1️⃣ 检查ch9344模块是否已加载"
if lsmod | grep -q ch9344; then
    echo -e "${GREEN}✓${NC} ch9344 驱动已加载"
    lsmod | grep ch9344
else
    echo -e "${RED}✗${NC} ch9344 驱动未加载"
    echo "  尝试手动加载..."
    sudo modprobe ch9344
    if lsmod | grep -q ch9344; then
        echo -e "${GREEN}✓${NC} ch9344 驱动加载成功"
    else
        echo -e "${RED}✗${NC} ch9344 驱动加载失败"
        exit 1
    fi
fi
echo ""

echo "2️⃣ 检查模块是否已安装到系统"
if modinfo ch9344 >/dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} ch9344 驱动已安装到系统"
    echo "  路径: $(modinfo ch9344 | grep filename | awk '{print $2}')"
else
    echo -e "${RED}✗${NC} ch9344 驱动未安装到系统"
fi
echo ""

echo "3️⃣ 检查开机自动加载配置"
if grep -q "^ch9344" /etc/modules 2>/dev/null; then
    echo -e "${GREEN}✓${NC} ch9344 已配置开机自动加载 (/etc/modules)"
else
    echo -e "${RED}✗${NC} ch9344 未配置开机自动加载"
fi
echo ""

echo "4️⃣ 检查串口设备"
if ls /dev/ttyCH9344USB* >/dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} 串口设备已创建 (共$(ls /dev/ttyCH9344USB* | wc -l)个)"
    ls -l /dev/ttyCH9344USB* | awk '{printf "  %-25s %s:%s  权限:%s\n", $NF, $3, $4, $1}'
else
    echo -e "${RED}✗${NC} 未找到串口设备"
    echo "  可能原因:"
    echo "    - USB设备未连接"
    echo "    - 驱动未正确加载"
fi
echo ""

echo "5️⃣ 检查udev规则"
if [ -f "/etc/udev/rules.d/99-ch9344.rules" ]; then
    echo -e "${GREEN}✓${NC} udev规则已安装"
    if grep -q "55d9" /etc/udev/rules.d/99-ch9344.rules; then
        echo -e "  ${GREEN}✓${NC} 包含55d9产品ID支持"
    fi
else
    echo -e "${YELLOW}⚠${NC} udev规则未安装"
fi
echo ""

echo "6️⃣ 检查用户权限"
if groups | grep -q dialout; then
    echo -e "${GREEN}✓${NC} 当前用户在dialout组"
else
    echo -e "${RED}✗${NC} 当前用户不在dialout组"
fi
echo ""

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 验证总结"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if lsmod | grep -q ch9344 && ls /dev/ttyCH9344USB* >/dev/null 2>&1; then
    echo -e "${GREEN}✅ 配置正常,可以运行程序${NC}"
    echo ""
    echo "运行orangepi_gateway:"
    echo "  cd ~/XiLi/orangepi"
    echo "  ./orangepi_gateway"
else
    echo -e "${RED}❌ 配置异常,需要检查${NC}"
    echo ""
    echo "故障排查:"
    echo "  1. 检查USB设备: lsusb | grep 1a86"
    echo "  2. 手动加载驱动: sudo modprobe ch9344"
    echo "  3. 查看内核日志: sudo dmesg | tail -50"
    echo "  4. 运行诊断: bash ~/XiLi/orangepi/scripts/diagnose_serial.sh"
fi
echo ""
